<template>
	<div class="system-user-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<!-- 搜索区域 -->
			<div class="system-user-search mb15">
				<el-input size="default" v-model="state.tableData.param.keyword" placeholder="请输入商品标题或描述" style="max-width: 220px"></el-input>
				<el-button size="default" type="primary" class="ml10" @click="fetchData(true)">
					<el-icon><ele-Search /></el-icon>
					查询
				</el-button>
				<el-button size="default" type="success" class="ml10" @click="onOpenAddOrEdit('add')" v-if="!state.isAdmin">
					<el-icon><ele-FolderAdd /></el-icon>
					新增商品
				</el-button>
			</div>

			<!-- 表格区域 -->
			<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%">
				<el-table-column type="index" label="序号" width="60" fixed="left" />
				<el-table-column prop="title" label="商品标题" show-overflow-tooltip min-width="150" fixed="left"></el-table-column>
				<!-- <el-table-column prop="userId" label="发布者ID" show-overflow-tooltip width="100"></el-table-column> -->
				<el-table-column prop="categoryName" label="商品分类" show-overflow-tooltip width="120">
                    <!-- 假设后端返回了 categoryName，如果没有，则显示 categoryId -->
                    <template slot-scope="scope">
                        {{ scope.row.categoryName || scope.row.categoryId }}
                    </template>
                </el-table-column>
				<el-table-column prop="price" label="价格" show-overflow-tooltip width="100">
                    <template slot-scope="scope">
                        ¥{{ scope.row.price }}
                    </template>
                </el-table-column>
				<!-- <el-table-column prop="originalPrice" label="原价" show-overflow-tooltip width="100">
                     <template slot-scope="scope">
                        {{ scope.row.originalPrice ? '¥' + scope.row.originalPrice : '-' }}
                    </template>
                </el-table-column> -->
                <el-table-column prop="imageUrls" label="图片" show-overflow-tooltip width="120">
                    <template slot-scope="scope">
                        <el-image
                            v-if="getFirstImageUrl(scope.row.imageUrls)"
                            style="width: 60px; height: 60px"
                            :src="getFirstImageUrl(scope.row.imageUrls)"
                            :preview-src-list="getPreviewImageUrls(scope.row.imageUrls)"
                            fit="cover"
                        >
                            <div slot="error" class="image-slot">
                                <i class="el-icon-picture-outline"></i>
                            </div>
                        </el-image>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
				<el-table-column prop="location" label="发布地点" show-overflow-tooltip width="120"></el-table-column>
				<el-table-column prop="status" label="商品状态" show-overflow-tooltip width="120">
                    <template slot-scope="scope">
                        <el-tag :type="getStatusTagType(scope.row.status)">
                            {{ formatStatus(scope.row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
				<!-- <el-table-column prop="viewCount" label="浏览次数" show-overflow-tooltip width="100"></el-table-column> -->
				<el-table-column prop="isNegotiable" label="可议价" show-overflow-tooltip width="80">
                    <template slot-scope="scope">
                        {{ scope.row.isNegotiable ? '是' : '否' }}
                    </template>
                </el-table-column>
				<el-table-column prop="createdAt" label="创建时间" show-overflow-tooltip width="160">
                     <template slot-scope="scope">
                        {{ scope.row.createDate | formatDate }}
                    </template>
                </el-table-column>
				<el-table-column prop="updatedAt" label="更新时间" show-overflow-tooltip width="160">
                    <template slot-scope="scope">
                        {{ scope.row.updateDate | formatDate }}
                    </template>
                </el-table-column>
				<el-table-column label="操作" width="250" fixed="right">
					<template slot-scope="scope">
						<el-button size="small" text type="primary" @click="onOpenAddOrEdit('edit', scope.row)">修改</el-button>
						<el-button size="small" text type="warning" @click="onOpenCommentsDialog(scope.row)">查看评论</el-button>
						<el-button size="small" text type="danger" @click="onRowDel(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页区域 -->
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 30, 50]"
				v-model:current-page="state.tableData.param.current"
				background
				v-model:page-size="state.tableData.param.limit"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableData.total"
			>
			</el-pagination>
		</el-card>

		<!-- 新增/编辑弹窗 -->
		<el-dialog :title="state.dialog.title" :visible.sync="state.dialog.isShowDialog" width="769px" @close="onDialogClose">
			<el-form ref="productFormRef" :model="state.ruleForm" :rules="state.formRules" size="default" label-width="120px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="商品标题" prop="title">
							<el-input v-model="state.ruleForm.title" placeholder="请输入商品标题" clearable></el-input>
						</el-form-item>
					</el-col>
					<!-- 
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="发布者用户ID" prop="userId">
							<el-input v-model="state.ruleForm.userId" placeholder="请输入用户ID"  controls-position="right" style="width:100%;"></el-input>
						</el-form-item>
					</el-col> -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="商品分类" prop="categoryId">
                            <!-- 假设有分类选择器或直接输入 -->
                            <el-select v-model="state.ruleForm.categoryId" placeholder="请选择商品分类" clearable filterable style="width:100%;">
                                <!-- 示例分类数据，实际应从API获取 -->
                                <el-option v-for="cat in state.categories" :key="cat.id" :label="cat.name" :value="cat.id"></el-option>
                            </el-select>
						</el-form-item>
					</el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="价格" prop="price">
							<el-input-number v-model="state.ruleForm.price" placeholder="请输入价格" :precision="2" :step="1" :min="0" controls-position="right" style="width:100%;"></el-input-number>
						</el-form-item>
					</el-col>
					<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="原价 (可选)" prop="originalPrice">
							<el-input-number v-model="state.ruleForm.originalPrice" placeholder="请输入原价" :precision="2" :step="1" :min="0" controls-position="right" style="width:100%;"></el-input-number>
						</el-form-item>
					</el-col> -->
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="发布地点" prop="location">
							<el-input v-model="state.ruleForm.location" placeholder="例如：上海市" clearable></el-input>
						</el-form-item>
					</el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="商品状态" prop="status">
							<el-select v-model="state.ruleForm.status" placeholder="请选择商品状态" clearable style="width:100%;">
                                <el-option label="可售" value="available"></el-option>
                                <el-option label="待确认" value="pending"></el-option>
                                <el-option label="已售" value="sold"></el-option>
                                <el-option label="已下架" value="delisted"></el-option>
                            </el-select>
						</el-form-item>
					</el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="是否可议价" prop="isNegotiable">
                            <el-radio-group v-model="state.ruleForm.isNegotiable">
                                <el-radio :label="true">是</el-radio>
                                <el-radio :label="false">否</el-radio>
                            </el-radio-group>
						</el-form-item>
					</el-col>
                    <!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="浏览次数" prop="viewCount">
							<el-input-number v-model="state.ruleForm.viewCount" placeholder="请输入浏览次数" :min="0" controls-position="right" style="width:100%;"></el-input-number>
						</el-form-item>
					</el-col> -->
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="商品描述" prop="description">
							<el-input type="textarea" v-model="state.ruleForm.description" placeholder="请输入商品描述" :rows="3" clearable></el-input>
						</el-form-item>
					</el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="商品图片链接" prop="imageUrls">
                            <!-- 简单文本输入，可后续升级为 el-upload -->
							<el-upload
							action="http://127.0.0.1:8080/sys/oss/upload"
							:headers="{'Token': token}"
							list-type="picture-card"
							:file-list="imagesUrlList"
							:on-success="handlePictureCardSuccess"
							:before-remove="handlePictureCardRemove"
							:on-preview="handlePictureCardPreview"
							>
							<i class="el-icon-plus"></i>
							</el-upload>
							
							<!-- <el-input type="textarea" v-model="state.ruleForm.imageUrls" placeholder="多个URL用逗号分隔，或输入JSON数组字符串" :rows="2" clearable></el-input> -->
                            <!-- <div class="el-upload__tip">提示：可输入多个图片URL，用英文逗号 (,) 分隔，或直接输入JSON数组格式的字符串。</div> -->
						</el-form-item>
					</el-col>
                    <!-- 创建/更新时间通常由后端自动处理，表单中一般为只读或不显示 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.dialog.type === 'edit'">
						<el-form-item label="创建时间">
							<el-date-picker
								v-model="state.ruleForm.createDate"
								type="datetime"
								placeholder="请选择时间"
								format="yyyy-MM-dd HH:mm:ss"
								value-format="yyyy-MM-dd HH:mm:ss"
								date-format="yyyy-MM-dd HH:mm:ss"
								time-format="HH:mm:ss"
							/>
							<!-- <el-input :value="state.ruleForm.createdAt | formatDate" placeholder="创建时间" readonly></el-input> -->
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.dialog.type === 'edit'">
						<el-form-item label="更新时间">
							<el-date-picker
								v-model="state.ruleForm.updateDate"
								type="datetime"
								placeholder="请选择时间"
								format="yyyy-MM-dd HH:mm:ss"
								value-format="yyyy-MM-dd HH:mm:ss"
								date-format="yyyy-MM-dd HH:mm:ss"
								time-format="HH:mm:ss"
							/>
							<!-- <el-input :value="state.ruleForm.updatedAt | formatDate" placeholder="更新时间" readonly></el-input> -->
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="onCancel" size="default">取 消</el-button>
				<el-button type="primary" @click="onSubmit" :loading="state.submitBtn.loading" size="default">{{ state.dialog.submitTxt }}</el-button>
			</div>
		</el-dialog>
		<el-dialog :visible.sync="dialogVisible">
			<img width="100%" :src="dialogImageUrl" alt="">
		</el-dialog>

		<!-- 评论弹窗 -->
		<<el-dialog
			title="商品评论"
			:visible.sync="state.commentsDialog.isShow"
			width="700px"
			@close="onCommentsDialogClose"
			:close-on-click-modal="false"
		>
			<div v-loading="state.commentsDialog.loading">
				<div v-if="state.commentsDialog.data.length > 0" class="comment-list-wrapper">
					<div v-for="comment in state.commentsDialog.data" :key="comment.commentsId" class="comment-item">
						<el-avatar :size="40" :src="comment.userAvatar" icon="el-icon-user-solid" class="comment-avatar"></el-avatar>
						<div class="comment-body">
							<div class="comment-header">
								<span class="comment-username">{{ comment.userName }}</span>
								<!-- 新增：删除评论按钮，仅管理员可见或评论发布者自己可见（这里简单处理为管理员可见） -->
								<el-button
									v-if="state.isAdmin" 
									type="text"
									size="mini"
									icon="el-icon-delete"
									class="comment-delete-btn"
									@click="onDeleteComment(comment)"
								>删除</el-button>
								<span v-else class="comment-time">{{ comment.createDate | formatDate }}</span>
							</div>
							<p class="comment-text">{{ comment.content }}</p>
							<!-- 如果不是管理员，且需要显示时间，则时间可以放在这里 -->
							<div v-if="!state.isAdmin && state.isAdmin !== undefined" class="comment-footer-time">
                                {{ comment.createDate | formatDate }}
                            </div>
						</div>
					</div>
				</div>
				<el-empty v-else description="暂无评论"></el-empty>

				<el-pagination
					v-if="state.commentsDialog.total > state.commentsDialog.param.limit"
					class="mt15"
					layout="prev, pager, next"
					:current-page.sync="state.commentsDialog.param.current"
					:page-size="state.commentsDialog.param.limit"
					:total="state.commentsDialog.total"
					@current-change="handleCommentPageChange"
				>
				</el-pagination>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="state.commentsDialog.isShow = false" size="default">关 闭</el-button>
			</span>
		</el-dialog>
		<!-- 评论弹窗结束 -->
	</div>
</template>

<script>
// 假设您的API封装在这个路径，请根据实际情况修改
import { useTbProductApi } from '@/api/tb/product'; // 假设API封装
import { useTbCommentApi } from '@/api/tb/comments';
import { Message, MessageBox } from 'element-ui'; // Vue 2 Element UI
import { Session } from '@/utils/storage';
// 简单日期格式化，您可以用更完善的库如 moment.js 或 day.js
const formatDateFilter = (value) => {
    if (!value) return '';
    const date = new Date(value);
    const y = date.getFullYear();
    const m = (date.getMonth() + 1).toString().padStart(2, '0');
    const d = date.getDate().toString().padStart(2, '0');
    const h = date.getHours().toString().padStart(2, '0');
    const i = date.getMinutes().toString().padStart(2, '0');
    const s = date.getSeconds().toString().padStart(2, '0');
    return `${y}-${m}-${d} ${h}:${i}:${s}`;
};


export default {
	name: 'TbProductManagement', // 组件名建议大驼峰
    filters: {
        formatDate: formatDateFilter
    },
	data() {
		return {
			dialogImageUrl: '',
        	dialogVisible: false,
			token : true,
			imagesUrlList: [],

			state: {
				isAdmin: Session.get('userInfo').username === 'admin',
				tableData: {
					data: [],
					total: 0,
					loading: false,
					param: {
						current: 1,
						limit: 10,
						keyword: '', // 搜索关键词
					},
				},
				
				commentsDialog: {
					isShow: false,
					loading: false,
					currentProductId: null,
					data: [],
					total: 0,
					param: {
						current: 1,
						limit: 10, // 每页显示5条评论
						productId: null, // 用于请求参数
					},
				},
				dialog: {
					isShowDialog: false,
					type: '', // 'add' or 'edit'
					title: '',
					submitTxt: '',
				},
                // 表单数据模型
				ruleForm: {
                    id: null, // 编辑时需要ID
					userId: null,
					categoryId: null,
					title: '',
					description: '',
					price: 0,
					originalPrice: null,
					imageUrls: '',
					location: '',
					status: 'available', // 默认可售
					viewCount: 0,
					isNegotiable: false, // 默认不可议价
					createdAt: '', // 在编辑时显示，新增时后端生成
					updatedAt: '', // 在编辑时显示，新增/编辑时后端生成
				},
                // 表单校验规则
                formRules: {
                    title: [{ required: true, message: '请输入商品标题', trigger: 'blur' }],
                    userId: [{ required: true, message: '请输入发布者用户ID', trigger: ['blur', 'change'] }],
                    categoryId: [{ required: true, message: '请选择商品分类', trigger: ['blur', 'change'] }],
                    price: [{ required: true, message: '请输入价格', trigger: ['blur', 'change'] }],
                    status: [{ required: true, message: '请选择商品状态', trigger: 'change' }],
                    isNegotiable: [{ required: true, message: '请选择是否可议价', trigger: 'change' }],
                },
				submitBtn: {
					loading: false,
					// type: '', // 这个可以移除，dialog.type 已经有了
				},
                categories: [], // 用于存放分类列表给下拉选择
                // 商品状态映射，用于表格显示
                statusMap: {
                    available: { text: '可售', type: 'success' },
                    pending: { text: '待确认', type: 'warning' },
                    sold: { text: '已售', type: 'info' },
                    delisted: { text: '已下架', type: 'danger' },
                },
			},
		};
	},
	methods: {
		handleRemove(file, fileList) {
	        console.log(file, fileList);
		},
		handlePictureCardSuccess(response, file, fileList){
			if(response.msg === 'success'){
				// 拆分url 和 文件名
				let url = response.url
				let name = response.name
				console.log(name)
				this.imagesUrlList.push({
					name: name,
					url: url,
				})
			}
			console.log(response, file, fileList);
		},
		
		handlePictureCardRemove(file, fileList){
			console.log(file, fileList);
			let findI = this.imagesUrlList.find((i)=>i.name === file.name && i.url === file.url);
			if(findI){
				this.imagesUrlList.splice(findI, 1)
			}
		},
		handlePictureCardPreview(file) {
			this.dialogImageUrl = file.url;
			this.dialogVisible = true;
		},
        // 获取商品列表数据
		fetchData(isSearch = false) {
            if (isSearch) {
                this.state.tableData.param.current = 1; // 搜索时回到第一页
            }
			this.state.tableData.loading = true;
			useTbProductApi()
				.list(this.state.tableData.param)
				.then((response) => {
                    if (response && response.data) {
                        this.state.tableData.data = response.data.records || [];
					    this.state.tableData.total = response.data.total || 0;
                    } else {
                        this.state.tableData.data = [];
                        this.state.tableData.total = 0;
                        Message.error('获取商品列表失败，数据格式不正确');
                    }
					this.state.tableData.loading = false;
				})
                .catch(err => {
                    this.state.tableData.loading = false;
                    Message.error(err.message || '获取商品列表失败');
                });
		},
        // （可选）获取分类列表，用于表单下拉选择
        fetchCategories() {
            // 假设有获取分类的API
            // useCategoryApi().listAll().then(res => { this.state.categories = res.data; });
            // 模拟数据
            this.state.categories = [
                { id: 1, name: '数码产品' },
                { id: 5, name: '手机 (数码产品子类)' },
                { id: 2, name: '服装鞋包' },
                { id: 3, name: '图书文具' },
            ];
        },
        // 初始化表单（用于新增）
        resetForm() {
            this.state.ruleForm = {
                id: null,
                userId: null,
                categoryId: null,
                title: '',
                description: '',
                price: 0,
                originalPrice: null,
                imageUrls: '',
                location: '',
                status: 'available',
                viewCount: 0,
                isNegotiable: false,
                createdAt: '',
                updatedAt: '',
            };
            // 清除表单校验结果
            if (this.$refs.productFormRef) {
                this.$refs.productFormRef.resetFields();
            }
        },
        // 打开新增/编辑弹窗
		onOpenAddOrEdit(type, row) {
            this.resetForm(); // 先重置表单
			this.state.dialog.type = type;
			this.imagesUrlList = []
			if (type === 'edit' && row) {
                // 深拷贝行数据到表单，避免直接修改表格数据
				this.state.ruleForm = JSON.parse(JSON.stringify(row));
				console.log(row)
				// 将图片转成 数组，拆分成name和url
				if(row.imageUrls){
					this.imagesUrlList = row.imageUrls.split(',').map(item => {
						let arr = item.split('/')
						return {
							name: arr[0],
							url: item,
						}
					})
				}
                // isNegotiable 在后端可能是 0/1，前端radio-group需要boolean
                this.state.ruleForm.isNegotiable = !!row.isNegotiable;
				this.state.dialog.title = '修改商品信息';
				this.state.dialog.submitTxt = '修 改';
			} else {
				this.state.dialog.title = '新增商品';
				this.state.dialog.submitTxt = '新 增';
                // 新增时可以设置一些默认值，如果resetForm中没有完全覆盖
                this.state.ruleForm.status = 'available';
                this.state.ruleForm.isNegotiable = false;
			}
			this.state.dialog.isShowDialog = true;
		},
        // 删除行
		onRowDel(row) {
			MessageBox.confirm(`确定要删除商品：“${row.title}” 吗？此操作将永久删除！`, '警告', {
				confirmButtonText: '确认删除',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					this.deleteProduct(row.id); // 传递ID进行删除
				})
				.catch(() => {
                    Message.info('已取消删除');
                });
		},
        // 执行删除操作
        deleteProduct(id) {
            useTbProductApi()
				.delete({ id }) // API通常需要一个包含id的对象或直接传递id
				.then(() => {
					Message.success('删除成功');
					this.fetchData(); // 刷新列表
				})
				.catch((err) => {
                    Message.error(err.message || '删除失败');
					// 可能不需要再次fetchData，取决于API设计，如果删除失败数据不变
				});
        },
        // 每页条数改变
		handleSizeChange(pageSize) {
			// this.state.tableData.data = []; // 无需手动清空，fetchData会覆盖
			this.state.tableData.param.limit = pageSize;
			this.fetchData();
		},
        // 当前页改变
		handleCurrentChange(current) {
			// this.state.tableData.data = []; // 无需手动清空
			this.state.tableData.param.current = current;
			this.fetchData();
		},
        // 弹窗关闭时的回调
        onDialogClose() {
            this.resetForm(); // 关闭时重置表单和校验
             if (this.$refs.productFormRef) {
                this.$refs.productFormRef.clearValidate(); // 确保清除校验状态
            }
        },
        // 取消按钮（弹窗内）
		onCancel() {
			this.state.dialog.isShowDialog = false;
            // onDialogClose 已经被 @close 触发，这里可以不用再调用 resetForm
		},
        // 提交按钮（弹窗内）
		onSubmit() {
            this.$refs.productFormRef.validate((valid) => {
                if (valid) {
                    this.state.submitBtn.loading = true;
                    const apiAction = this.state.dialog.type === 'edit' ? useTbProductApi().update : useTbProductApi().add;
                    const formData = { ...this.state.ruleForm };
                    // 确保 isNegotiable 提交的是 0 或 1 (如果后端需要数字)
                    formData.isNegotiable = formData.isNegotiable ? 1 : 0;
					// 处理图片上传
					if (this.imagesUrlList && this.imagesUrlList.length > 0) {
                        formData.imageUrls = this.imagesUrlList.map(item => item.url).join(',');
                    } else {
                        formData.imageUrls = '';
                    }
                    apiAction(formData)
                        .then(() => {
                            Message.success(this.state.dialog.type === 'edit' ? '修改成功' : '新增成功');
                            this.state.dialog.isShowDialog = false;
                            this.fetchData(); // 成功后刷新列表
                        })
                        .catch((err) => {
                            Message.error(err.message || (this.state.dialog.type === 'edit' ? '修改失败' : '新增失败'));
                        })
                        .finally(() => {
                            this.state.submitBtn.loading = false;
                        });
                } else {
                    Message.warning('请检查表单填写是否正确！');
                    return false;
                }
            });
		},

        // 表格中商品状态的格式化
        formatStatus(statusKey) {
            return this.state.statusMap[statusKey] ? this.state.statusMap[statusKey].text : statusKey;
        },
        getStatusTagType(statusKey) {
            return this.state.statusMap[statusKey] ? this.state.statusMap[statusKey].type : 'info';
        },
        // 获取图片链接中的第一张用于表格展示
        getFirstImageUrl(urls) {
            if (!urls) return '';
            try {
                // 尝试解析JSON数组
                const parsedUrls = JSON.parse(urls);
                if (Array.isArray(parsedUrls) && parsedUrls.length > 0) {
                    return parsedUrls[0];
                }
            } catch (e) {
                // 解析失败，则按逗号分隔
                const urlArray = urls.split(',');
                if (urlArray.length > 0 && urlArray[0].trim() !== '') {
                    return urlArray[0].trim();
                }
            }
            return ''; // 如果都无效，返回空
        },
        // 获取所有图片链接用于预览
        getPreviewImageUrls(urls) {
            if (!urls) return [];
            try {
                const parsedUrls = JSON.parse(urls);
                if (Array.isArray(parsedUrls)) {
                    return parsedUrls.filter(url => url && typeof url === 'string' && url.trim() !== '');
                }
            } catch (e) {
                const urlArray = urls.split(',');
                return urlArray.map(url => url.trim()).filter(url => url !== '');
            }
            return [];
        },
		// 打开评论弹窗并加载第一页评论
		onOpenCommentsDialog(row) {
			this.state.commentsDialog.isShow = true;
			this.state.commentsDialog.currentProductId = row.id; // 或 productId，根据你的商品对象字段
			this.state.commentsDialog.param.productId = row.id;
			this.state.commentsDialog.param.current = 1; // 重置到第一页
			this.fetchComments();
		},

		// 获取评论列表数据
		fetchComments() {
			if (!this.state.commentsDialog.param.productId) return;
			this.state.commentsDialog.loading = true;
			// 假设你的 API 请求库是 useTbCommentsApi，或者直接使用 axios/fetch
			// 替换为你的实际API调用
			// import { useTbCommentsApi } from '@/api/tb/comments'; // 假设API封装

			// 模拟 API 路径，请替换
			const commentsApiUrl = `http://192.168.1.130:8080/tb/comments/list`;
			const params = {
				productId: this.state.commentsDialog.param.productId,
				current: this.state.commentsDialog.param.current,
				limit: this.state.commentsDialog.param.limit,
			};

			// 实际项目中请使用你封装的请求方法
			// 这里用 fetch 举例，你需要根据你的项目配置调整
			useTbCommentApi().list(params).then(res => { 
				if (res.success && res.data) {
					this.state.commentsDialog.data = res.data.records || [];
					this.state.commentsDialog.total = res.data.total || 0;
				} else {
					this.state.commentsDialog.data = [];
					this.state.commentsDialog.total = 0;
					Message.error(res.msg || '获取评论列表失败');
				}

			}).catch(err => {
				Message.error(err.message || '获取评论列表请求异常');
				this.state.commentsDialog.data = [];
				this.state.commentsDialog.total = 0;
			})
			.finally(() => {
				this.state.commentsDialog.loading = false;
			});

		},

		// 评论弹窗分页改变
		handleCommentPageChange(page) {
			this.state.commentsDialog.param.current = page;
			this.fetchComments();
		},

		// 关闭评论弹窗时的回调
		onCommentsDialogClose() {
			// 重置评论弹窗状态
			this.state.commentsDialog.currentProductId = null;
			this.state.commentsDialog.param.productId = null;
			this.state.commentsDialog.data = [];
			this.state.commentsDialog.total = 0;
			this.state.commentsDialog.param.current = 1;
			this.state.commentsDialog.loading = false; // 确保 loading 状态也重置
		},
		// 新增：删除评论
		onDeleteComment(comment) {
			MessageBox.confirm(`确定要删除用户 “${comment.userName}” 的这条评论吗？`, '警告', {
				confirmButtonText: '确认删除',
				cancelButtonText: '取消',
				type: 'warning',
			})
			.then(() => {
				this.executeDeleteComment(comment.commentsId);
			})
			.catch(() => {
				Message.info('已取消删除评论');
			});
		},

		// 新增：执行删除评论的API调用
		executeDeleteComment(commentId) {
			this.state.commentsDialog.loading = true; // 可以加一个loading效果
			useTbCommentApi().delete({ commentsId: commentId }) // 假设 useTbCommentApi().delete() 内部处理了请求
			.then(res => {
				if (res.success) { // 假设后端返回 { success: true }
					Message.success('评论删除成功');
					// 刷新评论列表
					// 如果删除的是当前页的最后一条，且不是第一页，可以考虑返回上一页
					if (this.state.commentsDialog.data.length === 1 && this.state.commentsDialog.param.current > 1) {
						this.state.commentsDialog.param.current -= 1;
					}
					this.fetchComments(); // 重新获取当前页的评论
				} else {
					Message.error(res.msg || '删除评论失败');
				}
			})
			.catch(err => {
				Message.error(err.message || '删除评论请求异常');
			})
			.finally(() => {
			});
		},
	},
	mounted() { // Vue 2 使用 mounted
		// console.log(Session.get('userInfo'))
		if(Session.get('userInfo')){
			this.state.isAdmin =Session.get('userInfo').userName === 'admin'
		}
		this.fetchData();
        this.fetchCategories(); // 获取分类数据
	},
};
</script>

<style scoped>
/* 可以添加一些自定义样式，例如让表格中的图片更好看 */
.el-table .el-image {
    border-radius: 4px;
}
.el-table .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 20px;
}
.el-form-item .el-input-number,
.el-form-item .el-select {
    width: 100%; /* 让数字输入框和选择器宽度占满 */
}
.dialog-footer {
    text-align: right;
    margin-top: 20px; /* 给弹窗底部按钮一些间距 */
}

/* 评论列表样式 */
.comment-header {
	display: flex;
	justify-content: space-between;
	align-items: center; /* 保持垂直居中 */
	margin-bottom: 5px;
}
.comment-username {
	font-weight: bold;
	color: #303133;
	font-size: 14px;
	margin-right: auto; /* 让用户名占据左边空间，将时间和删除按钮推到右边 */
}
.comment-time {
	font-size: 12px;
	color: #909399;
	margin-left: 10px; /* 和删除按钮之间留点空隙 */
}
.comment-delete-btn {
	font-size: 12px; /* 调整删除按钮大小 */
	padding: 0 5px; /* 调整删除按钮padding */
	margin-left: 10px; /* 和用户名之间留点空隙 */
	color: #F56C6C; /* 危险颜色 */
}
.comment-delete-btn:hover {
	color: #f78989;
}
.comment-footer-time { /* 如果时间放在内容下方 */
    text-align: right;
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
}
</style>